<?php

namespace app\admin\controller\article;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 
 *
 * @icon fa fa-file
 */
class Article extends Backend
{

    /**
     * Article模型对象
     */
    protected $model = null;
    protected $noNeedRight = ['changestatus'];
    protected $noNeedLogin = ['changestatus'];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid = false;
        $this->model = model('Article');
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 默认排序：当未指定排序字段时，按id DESC
            if (empty($sort)) {
                $sort = 'id';
            }
            if (empty($order)) {
                $order = 'DESC';
            }

            // 添加城市和学校过滤逻辑
            $cityId = $this->request->get('city_id');
            $schoolId = $this->request->get('school_id');

            // 创建额外的查询条件数组
            $extraWhere = [];

            // 根据用户组进行数据过滤
            $admin = $_SESSION['think']['admin'] ?? [];
            if (isset($admin['group_id'])) {
                if ($admin['group_id'] == 3) { // 学校管理用户
                    if (isset($admin['school_id']) && !empty($admin['school_id'])) {
                        $extraWhere[] = ['school_id', 'like', '%' . $admin['school_id'] . '%'];
                    }
                } elseif ($admin['group_id'] == 8) { // 社区管理用户
                    if (isset($admin['city_id']) && !empty($admin['city_id'])) {
                        $extraWhere[] = ['city_id', 'like', '%' . $admin['city_id'] . '%'];
                        $extraWhere[] = ['column_id', '=', 26];
                    }
                }
            }

            // 前端筛选条件
            if (!empty($cityId)) {
                $extraWhere[] = ['city_id', 'like', '%' . $cityId . '%'];
            }
            if (!empty($schoolId)) {
                $extraWhere[] = ['school_id', 'like', '%' . $schoolId . '%'];
            }

            $query = $this->model->where($where);

            // 添加额外的查询条件
            foreach ($extraWhere as $condition) {
                $query->where($condition[0], $condition[1], $condition[2]);
            }

            $total = $query->order("weigh asc")->order($sort, $order)->count();

            $list = $this->model->where($where);

            // 添加额外的查询条件
            foreach ($extraWhere as $condition) {
                $list->where($condition[0], $condition[1], $condition[2]);
            }



            // 只有当排序字段不是 weigh 时，才添加额外的排序
            if ($sort != 'weigh') {
                $list = $list->order($sort, $order);
            }else{
                $list = $list->order("id easc");
            }

            $list = $list->limit($offset, $limit)
                ->select();
            //$sql = $this->model->getLastSql();
            $list = collection($list)->toArray();
            for ($i = 0; $i < count($list); $i++) {
                $list[$i]['city_id'] = model('Cityarea')->getCity_idTextAttr($list[$i]['city_id'], $list[$i]);
                $list[$i]['school_id'] = model('School')->getSchool_idTextAttr($list[$i]['school_id'], $list[$i]);
                $list[$i]['column_id'] = model('Column')->getColumn_idTextAttr($list[$i]['column_id'], $list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    // 验证栏目是否已选择
                    if (empty($params['column_id'])) {
                        return json(['code' => 0, 'msg' => '请先选择栏目']);
                    }

                    // 社区管理员权限控制：只能选择社区信息栏目
                    if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 8) {
                        $columnInfo = model('Column')->where('id', $params['column_id'])->find();
                        if (!$columnInfo || $columnInfo['column'] !== '社区信息') {
                            return json(['code' => 0, 'msg' => '社区管理员只能选择社区信息栏目']);
                        }
                    }

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    $user = $this->auth->getUserInfo();
                    unset($params['id']);
                    $params['status'] = 1;
                    $params['userid'] = $user['id'];

                    // 自动插入session中的城市和学校ID
                    $admin = $_SESSION['think']['admin'] ?? [];
                    if (isset($admin['city_id']) && !empty($admin['city_id'])) {
                        $params['city_id'] = $admin['city_id'];
                    }
                    if (isset($admin['school_id']) && !empty($admin['school_id'])) {
                        $params['school_id'] = $admin['school_id'];
                    }

                    // 处理关联数据
                    $schoolIds = $this->processRelationIds($params, 'school_id', $user['school_id']);
                    $ocationIds = $this->processRelationIds($params, 'ocation_id');
                    $classesIds = $this->processRelationIds($params, 'classes_id');

                    // 移除手动设置的时间字段，让模型自动处理
                    unset($params['update_time'], $params['create_time']);

                    // 开启事务
                    \think\Db::startTrans();
                    try {
                        $result = $this->model->allowField(true)->save($params);
                        if ($result !== false) {
                            $articleId = $this->model->id;

                            // 插入关联表数据
                            $this->insertRelationData($articleId, $schoolIds, 'fa_article_school', 'school_id');
                            $this->insertRelationData($articleId, $ocationIds, 'fa_article_ocation', 'ocation_id');
                            $this->insertRelationData($articleId, $classesIds, 'fa_article_classes', 'classes_id');

                            \think\Db::commit();
                            return json_encode(['code' => 1, 'msg' => '保存成功']);
                        } else {
                            \think\Db::rollback();
                            return json(['code' => 0, 'msg' => $this->model->getError()]);
                        }
                    } catch (\Exception $e) {
                        \think\Db::rollback();
                        return json(['code' => 0, 'msg' => $e->getMessage()]);
                    }
                } catch (\think\exception\PDOException $e) {
                    return json(['code' => 0, 'msg' => $e->getMessage()]);
                } catch (\think\Exception $e) {
                    return json(['code' => 0, 'msg' => $e->getMessage()]);
                }
            }
            return json(['code' => 0, 'msg' => __('Parameter %s can not be empty', '')]);
        }

        // 设置管理员配置信息到前端
        $user = $this->auth->getUserInfo();
        $this->assignconfig("admin", [
            'id' => $user['id'],
            'username' => $user['username'],
            'city_id' => $user['city_id'] ?? '',
            'school_id' => $user['school_id'] ?? '',
            'rel_type' => $user['rel_type'] ?? '',
            'rel_id' => $user['rel_id'] ?? '',
            'group_id' => $user['group_id'] ?? ''
        ]);
        $is_community_admin = isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 8;
        $this->view->assign('is_community_admin', $is_community_admin);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();

            // 处理视频上传 - with existence check
            if (isset($_FILES['video']) && $_FILES['video']['size'] > 0) {
                $video = $this->request->file('video');
                $videoConfig = [
                    'mimetype' => 'video/*',
                    'maxsize' => 1024 * 1024 * 100 // 100MB
                ];
                $videoInfo = Service\Upload::instance()->upload($video, 'video', 0, $videoConfig);
                if ($videoInfo) {
                    $params['video'] = $videoInfo->url;
                }
            }

            // 处理图片上传 - with existence check
            if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
                $image = $this->request->file('image');
                $imageConfig = [
                    'mimetype' => 'image/*',
                    'maxsize' => 1024 * 1024 * 10 // 10MB
                ];
                $imageInfo = Service\Upload::instance()->upload($image, 'image', 0, $imageConfig);
                if ($imageInfo) {
                    $params['image'] = $imageInfo->url;
                }
            }

            if ($params) {
                try {
                    // 验证栏目是否已选择
                    if (empty($params['row']['column_id'])) {
                        $this->error('请先选择栏目');
                    }

                    // 社区管理员权限控制：只能选择社区信息栏目
                    if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 8) {
                        $columnInfo = model('Column')->where('id', $params['row']['column_id'])->find();
                        if (!$columnInfo || $columnInfo['column'] !== '社区信息') {
                            $this->error('社区管理员只能选择社区信息栏目');
                        }
                    }

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $title = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $title . '.edit' : $title) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $user = $this->auth->getUserInfo();
                    $params['row']['userid'] = $user['id'];

                    // 处理关联数据
                    $schoolIds = $this->processRelationIds($params['row'], 'school_id', $user['school_id']);
                    $params['row']['school_id'] = join(",", $schoolIds);
                    $ocationIds = $this->processRelationIds($params['row'], 'ocation_id');
                    $params['row']['ocation_id'] = join(",", $ocationIds);
                    $classesIds = $this->processRelationIds($params['row'], 'classes_id');
                    $params['row']['classes_id'] = join(",", $classesIds);

                    // 移除手动设置的时间字段，让模型自动处理
                    unset($params['row']['update_time'], $params['row']['create_time']);

                    // 开启事务
                    \think\Db::startTrans();
                    try {
                        $result = $row->allowField(true)->save($params['row']);
                        if ($result !== false) {
                            $articleId = $row->id;

                            // 删除旧的关联数据
                            $this->deleteRelationData($articleId, 'fa_article_school');
                            $this->deleteRelationData($articleId, 'fa_article_ocation');
                            $this->deleteRelationData($articleId, 'fa_article_classes');

                            // 插入新的关联表数据
                            $this->insertRelationData($articleId, $schoolIds, 'fa_article_school', 'school_id');
                            $this->insertRelationData($articleId, $ocationIds, 'fa_article_ocation', 'ocation_id');
                            $this->insertRelationData($articleId, $classesIds, 'fa_article_classes', 'classes_id');

                            \think\Db::commit();
                            return json_encode(['code' => 1, 'msg' => '保存成功']);
                        } else {
                            \think\Db::rollback();
                            $this->error($row->getError());
                        }
                    } catch (\Exception $e) {
                        \think\Db::rollback();
                        $this->error($e->getMessage());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 设置管理员配置信息到前端
        $user = $this->auth->getUserInfo();
        $this->assignconfig("admin", [
            'id' => $user['id'],
            'username' => $user['username'],
            'city_id' => $user['city_id'] ?? '',
            'school_id' => $user['school_id'] ?? '',
            'rel_type' => $user['rel_type'] ?? '',
            'rel_id' => $user['rel_id'] ?? '',
            'group_id' => $user['group_id'] ?? ''
        ]);
        $is_community_admin = isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 8;
        $this->view->assign('is_community_admin', $is_community_admin);
        $row["ocation_id"] = array_map('intval', array_filter(preg_split("/./", $row["ocation_id"] ?? ''), function ($value) {
            return !empty(trim($value));
        }));
        $row["classes_id"] =  array_map('intval', array_filter(preg_split("/./", $row["classes_id"] ?? ''), function ($value) {
            return !empty(trim($value));
        }));
        $row["school_id"] = array_map('intval', array_filter(preg_split("/./", $row["school_id"] ?? ''), function ($value) {
            return !empty(trim($value));
        }));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row = $this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL)
    {
        $where = "";
        $page = 1;
        $pagesize = 50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    $where = "where 1=0";
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " or $keyField='{$nn[$i]}'";
                    }
                }
            }
        }
        $sql = "select id,title name from dev002_gxyusheng.fa_article $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

        //$tree = Tree::instance();
        //$tree->init($list, 'pid');
        //if(isset($keyValue)&&$keyValue!=""){
        //}else{
        //    $list=$tree->getTreeList($tree->getTreeArray(0), 'name');
        //    //array_unshift($list,array("name"=>"无父级","pid"=>0,"weigh"=>9999));
        //}

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_article $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    /**
     * 更改状态
     */
    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    /**
     * 物理删除文章
     */
    public function del($ids = null)
    {
        $ids = $this->request->param('ids');
        if (empty($ids)) {
            $this->error('没有选中要删除的记录!');
        }

        // 支持批量删除，将ids转换为数组
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }

        // 获取当前用户信息
        $user = $this->auth->getUserInfo();
        $userGroupId = $user['group_id'] ?? 0;
        $userId = $user['id'] ?? 0;

        foreach ($ids as $id) {
            $id = intval($id);
            if ($id <= 0) {
                continue;
            }

            // 获取文章信息
            $article = $this->model->where('id', $id)->find();
            if (!$article) {
                continue;
            }

            // 权限检查：只能删除自己创建的文章，或者管理员可以删除所有文章
            if ($article['userid'] != $userId && !in_array($userGroupId, [1, 2])) {
                //$this->error('您只能删除自己创建的文章，或者需要管理员权限!');
            }

            // 社区管理员权限检查：只能删除社区信息栏目的文章
            if ($userGroupId == 8) {
                $columnInfo = model('Column')->where('id', $article['column_id'])->find();
                if (!$columnInfo || $columnInfo['column'] !== '社区信息') {
                    //$this->error('社区管理员只能删除社区信息栏目的文章!');
                }
            }

            // 删除关联表数据
            $this->deleteRelationData($id, 'fa_article_school');
            $this->deleteRelationData($id, 'fa_article_ocation');
            $this->deleteRelationData($id, 'fa_article_classes');

            // 删除主表记录
            $deleteResult = $this->model->where('id', $id)->delete();
            if (!$deleteResult) {
                $this->error('删除文章ID:' . $id . '失败!');
            }
        }

        $this->success('删除成功!', '', ['refresh' => true]);
    }

    /**
     * 批量操作
     */
    public function multi($ids = null)
    {
        $ids = $this->request->param('ids');
        $action = $this->request->param('action');

        if (empty($ids)) {
            $this->error('没有选中要操作的记录!');
        }

        if (empty($action)) {
            $this->error('没有指定操作类型!');
        }

        // 支持批量操作，将ids转换为数组
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }

        // 获取当前用户信息
        $user = $this->auth->getUserInfo();
        $userGroupId = $user['group_id'] ?? 0;
        $userId = $user['id'] ?? 0;

        foreach ($ids as $id) {
            $id = intval($id);
            if ($id <= 0) {
                continue;
            }

            // 获取文章信息
            $article = $this->model->where('id', $id)->find();
            if (!$article) {
                continue;
            }

            // 权限检查：只能操作自己创建的文章，或者管理员可以操作所有文章
            if ($article['userid'] != $userId && !in_array($userGroupId, [1, 2])) {
                $this->error('您只能操作自己创建的文章，或者需要管理员权限!');
            }

            // 社区管理员权限检查：只能操作社区信息栏目的文章
            if ($userGroupId == 8) {
                $columnInfo = model('Column')->where('id', $article['column_id'])->find();
                if (!$columnInfo || $columnInfo['column'] !== '社区信息') {
                    $this->error('社区管理员只能操作社区信息栏目的文章!');
                }
            }

            // 根据操作类型执行相应操作
            switch ($action) {
                case 'del':
                    // 删除关联表数据
                    $this->deleteRelationData($id, 'fa_article_school');
                    $this->deleteRelationData($id, 'fa_article_ocation');
                    $this->deleteRelationData($id, 'fa_article_classes');

                    // 删除主表记录
                    $deleteResult = $this->model->where('id', $id)->delete();
                    if (!$deleteResult) {
                        $this->error('删除文章ID:' . $id . '失败!');
                    }
                    break;

                case 'status=normal':
                    // 设置为正常状态
                    $this->model->where('id', $id)->update(['status' => 1]);
                    break;

                case 'status=hidden':
                    // 设置为隐藏状态
                    $this->model->where('id', $id)->update(['status' => 0]);
                    break;

                default:
                    $this->error('不支持的操作类型: ' . $action);
            }
        }

        // 根据操作类型返回相应消息
        switch ($action) {
            case 'del':
                $this->success('批量删除成功!', '', ['refresh' => true]);
                break;
            case 'status=normal':
                $this->success('批量设置为正常状态成功!', '', ['refresh' => true]);
                break;
            case 'status=hidden':
                $this->success('批量设置为隐藏状态成功!', '', ['refresh' => true]);
                break;
            default:
                $this->success('批量操作成功!', '', ['refresh' => true]);
        }
    }

    /**
     * 排序
     */
    public function sort()
    {
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids');
            if ($ids) {
                $arr = explode(',', $ids);
                foreach ($arr as $k => $v) {
                    $this->model->where('id', $v)->update(['weigh' => count($arr) - $k]);
                }
                $this->success();
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 处理关联ID数据
     * @param array $params 参数数组
     * @param string $field 字段名
     * @param mixed $defaultValue 默认值
     * @return array 处理后的ID数组（数字数组）
     */
    private function processRelationIds(&$params, $field, $defaultValue = null)
    {
        $ids = [];

        // 获取字段值
        $value = isset($params[$field]) ? $params[$field] : $defaultValue;

        if (!empty($value)) {
            // 如果是数组，转换为数字数组
            if (is_array($value)) {
                $ids = array_map('intval', array_filter($value));
            } else {
                // 如果是字符串，使用辅助方法转换为数字数组
                $ids = $this->stringToIntArray($value);
            }

            // 去重并重新索引
            $ids = array_values(array_unique($ids));

            // 将ID数组转换为逗号分隔的字符串存储到参数中
            $params[$field] = $this->intArrayToString($ids);
        } else {
            $params[$field] = '';
        }

        return $ids;
    }

    /**
     * 插入关联表数据
     * @param int $articleId 文章ID
     * @param array $ids 关联ID数组
     * @param string $tableName 表名
     * @param string $fieldName 字段名
     */
    private function insertRelationData($articleId, $ids, $tableName, $fieldName)
    {
        if (empty($ids) || empty($articleId)) {
            return;
        }

        $data = [];
        $currentTime = date('Y-m-d H:i:s');

        foreach ($ids as $id) {
            if (!empty($id)) {
                $data[] = [
                    'article_id' => $articleId,
                    $fieldName => $id,
                    'create_time' => $currentTime,
                    'update_time' => $currentTime,
                    'status' => 1,
                    'weigh' => 0
                ];
            }
        }

        if (!empty($data)) {
            \think\Db::name(str_replace('fa_', '', $tableName))->insertAll($data);
        }
    }

    /**
     * 删除关联表数据
     * @param int $articleId 文章ID
     * @param string $tableName 表名
     */
    private function deleteRelationData($articleId, $tableName)
    {
        if (empty($articleId)) {
            return;
        }

        \think\Db::name(str_replace('fa_', '', $tableName))
            ->where('article_id', $articleId)
            ->delete();
    }

    /**
     * 将逗号分隔的字符串转换为数字数组
     * @param string $str 逗号分隔的字符串
     * @return array 数字数组
     */
    private function stringToIntArray($str)
    {
        if (empty($str)) {
            return [];
        }

        return array_map('intval', array_filter(explode(',', $str), function ($value) {
            return !empty(trim($value));
        }));
    }

    /**
     * 将数字数组转换为逗号分隔的字符串
     * @param array $arr 数字数组
     * @return string 逗号分隔的字符串
     */
    private function intArrayToString($arr)
    {
        if (empty($arr) || !is_array($arr)) {
            return '';
        }

        return implode(',', array_map('intval', $arr));
    }
}
